<!--
 * @Date: 2022-04-22 20:56:54
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-04-23 14:03:08
 * @FilePath: \weibovue\src\components\typeWriter.vue
 * @Description: 打字机
-->
<template>
  <div class="writerBox">
    <div>
      <p class="typewriter">{{ typewriter }}</p>
      <span>|</span>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, PropType, ref, watch } from "vue";
import useScroll from "../hooks/useScroll";
const typewriter = ref("");
const i = ref(0);
const arrI = ref(0);
const timer = ref<NodeJS.Timeout>();
const props = defineProps({
  str: {
    type: Array as PropType<String[]>,
  },
  speed: {
    type: Number,
    default: 300,
  },
});
let strVal = ref(props.str![arrI.value]);
let speed = ref(props.speed);
const { isFlag } = useScroll(900);
const writing = () => {
  if (i.value <= strVal.value!.length) {
    typewriter.value = strVal.value!.slice(0, i.value++);
    timer.value = setTimeout(() => {
      writing();
    }, speed.value);
  } else {
    arrI.value += 1;
    i.value = 0;
    strVal.value = props.str![arrI.value];
    if (arrI.value == props.str?.length!) {
      arrI.value = 0;
      strVal.value = props.str![arrI.value];
      writing();
    }
    clearTimeout(timer.value!);
    timer.value = setTimeout(() => {
      writing();
    }, speed.value);
  }
};
onMounted(() => {
  writing();
});
watch(
  () => isFlag.value,
  (val) => {
    if (val) {
      clearTimeout(timer.value!);
    } else {
      writing();
    }
  },
);
</script>
<style lang="less" scoped>
.writerBox {
  div {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    span {
      animation: shan 0.7s infinite;
    }
  }
}

@keyframes shan {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
</style>
